<template>
  <div>
    <div v-show="isComplete==''&&isEnd" class="write">
      <!-- form 表单-->
      <Write ref="write" :senderEmail="form.senderEmail" @getSendEmail="getSendEmail" @review="review"
             :emailSubject="form.emailSubject" @getInfoWrite="getInfoWrite" @getCancel="getCancel"
             :disabled="isLoading"
             @toApproval="toApproval"></Write>
      <!-- 编辑器操作-->
      <MakeBtn ref="makeBtn"
               @getInfoMake="getInfoMake" @insertEditor="insertEditor">
        <UE :config="{initialFrameHeight: 600}" ref="childEdit" :catchData="getContent" :htmlContent="form.emailContent"
            :ID="id"
            @ready="ready">
          <div class="common-edit">
            <script :id="id" type="text/plain" style="width: 100%"></script>
          </div>
        </UE>
      </MakeBtn>
      <!--发件人信息-->
      <div class="info">
        <h1>发件人: {{form.senderNickName}}&nbsp;&nbsp; {{form.senderEmail}}
        </h1>
        <el-checkbox-group v-model="checkList">
          <el-checkbox label="紧急"></el-checkbox>
          <el-checkbox label="回执"></el-checkbox>
          <el-checkbox label="定时发送"></el-checkbox>
          <el-checkbox label="追踪邮件"></el-checkbox>
        </el-checkbox-group>
      </div>
      <!--操作按钮-->
      <div class="make-btn">
        <el-button class="active" @click="$refs.write.sendEmail('')"><i class="icon-fasong iconfont"></i>发送</el-button>
        <el-button @click="$refs.write.toApproval()">提交审批</el-button>
        <el-button @click="$refs.write.sendEmail(2)">存草稿</el-button>
      </div>
      <DialogTargetTime ref="dialogTargetTime" @getRightTime="getRightTime"></DialogTargetTime>
      <DialogApproval ref="dialogApproval" @reset="reset"></DialogApproval>
    </div>
    <SuccessInbox v-show="name!='emailListCustomerTab'&&isComplete!=''" ref="successInbox" :currentID="id"></SuccessInbox>
    <SuccessCustomerbox v-show="name=='emailListCustomerTab'&&isComplete!=''"
                        ref="successCustomerInbox"></SuccessCustomerbox>
  </div>
</template>
<script>
    import DialogTargetTime from '@/components/mail/DialogTargetTime'
    import DialogApproval from '@/components/mail/DialogApproval'
    import Write from '@/components/mail/write/WriteInbox'
    import MakeBtn from '@/components/mail/write/MakeBtnInbox'
    import {sendEmail} from "@/api/mail/write"
    import SuccessInbox from "@/components/mail/success/SuccessInbox"
    import SuccessCustomerbox from "@/components/mail/success/SuccessCustomerbox"
    import {dealStr} from '@/util/util'
    import {mapGetters, mapState} from "vuex"
    import UE from '@/components/ueditor/ueInbox'

    export default {
        name: 'write',
        props: ['info', 'file', 'id', 'name'],
        components: {Write, MakeBtn, DialogTargetTime, DialogApproval, UE, SuccessInbox, SuccessCustomerbox},
        data() {
            return {
                form: {
                    addresseeEmail: [],//收件人邮箱数组
                    emailCarbonCopy: [],//抄送数组
                    emailSecretDelivery: [],//密送数组
                    emailHtmlpicList: [],//附件列表
                    emailSubject: '',//主题
                    emailContent: '',//邮件内容
                    emailReceipt: 0,//是否回执 0-默认不回执，1-回执
                    emaileDelivery: 0,//投递状态  （紧急与非紧急） 0-默认常规，2-紧急
                    monocular: 0,//群发单显
                    emailTrack: 0,//0 - 不追踪  1 - 追踪
                    emailSendTiming: '', //邮件定时发送时间
                    senderEmail: '',//发件人邮箱
                    senderNickName: '',//发件人昵称
                    boxId: '',
                    emailOriginalId: ''
                },
                pickerOptions: {
                    disabledDate: time => {
                        return time.getTime() < Date.now() - 8.64e7
                    }
                },
                checkList: ['追踪邮件'],
                isEnd: false,
                isComplete: '',
                isLoading: false
            }
        },
        computed: {
            ...mapState(['common']),
            ...mapGetters(["userInfo"]),
        },
        watch: {
            checkList(val, old) {
                let el = this.getArrDifference(val, old);
                if (el[0] == '定时发送') {
                    if (!old.includes('定时发送')) {
                        this.$refs.dialogTargetTime.init();
                    } else {
                        this.form.emailSendTiming = '';
                    }
                }
            }
        },
        methods: {
            ready() {
                this.dealInit();
            },
            getContent(val) {
                this.form.emailContent = val;
                this.getInfoMake(this.form)
            },
            dealInit() {
                if (this.info) {
                    const info = JSON.parse(this.info);
                    if (info.hasOwnProperty('emailTrack')) {//回复全部
                        this.dealEdit(info);
                    } else {//回复
                        let res;
                        if (info.customer.indexOf(',')) {
                            res = info.customer.split(',');
                        } else {
                            res = [info.customer]
                        }
                        this.form.emailOriginalId = info.emailOriginalId;
                        this.$refs.childEdit.getInit(info.emailContent);
                        this.$refs.write.customerInit(res, info.emailSubject);
                        this.$refs.write.initSend(info.senderEmail);
                    }
                } else {
                    let email = this.common.currentEmail;
                    if (email == '') { //全部邮箱时候 - 选择默认的
                        this.common.emailList.map(item => {
                            if (item.isDefault) {
                                this.form.senderEmail = item.emailAddr;
                                return;
                            }
                        })
                    } else {
                        this.form.senderEmail = email;
                    }
                    this.$refs.write.initSend(this.form.senderEmail);
                }
                //来自作为附件发送
                if (this.file) {
                    const file = JSON.parse(this.file);
                    this.form.emailHtmlpicList =file.emailHtmlpicList;
                    //初始化附件
                    this.$refs.makeBtn.initFile(file.emailHtmlpicList)
                    //初始化主题
                    this.$refs.write.initSubject(file.emailSubject);
                }
                this.form.senderNickName = this.userInfo.account;//获取用户名
                this.isEnd = true;
            },
            dealEdit(detail) {
                this.checkList = [];
                this.form.emailContent = detail.emailContent;
                this.form.emailOriginalId = detail.emailOriginalId;
                this.form.emailSubject = detail.emailSubject;
                this.form.addresseeEmail = dealStr(detail.addresseeEmail);
                this.form.emailCarbonCopy = dealStr(detail.emailCarbonCopy);
                this.form.emailSecretDelivery = dealStr(detail.emailSecretDelivery);
                this.form.emailHtmlpicList = detail.emailHtmlpicList;
                this.form.emailSendTiming = detail.emailSendTiming;
                this.form.emailReceipt = parseInt(detail.emailReceipt);
                this.form.emaileDelivery = parseInt(detail.emaileDelivery);
                this.form.emailTrack = detail.emailTrack;
                this.form.monocular = parseInt(detail.monocular);
                if (this.form.monocular == 1) this.checkList.push('群发单显');
                if (this.form.emailReceipt == 1) this.checkList.push('回执');
                if (this.form.emaileDelivery == 2) this.checkList.push('紧急');
                if (this.form.emailTrack == 1) {
                    this.checkList.push('追踪邮件')
                } else {
                    this.checkList.splice(this.checkList.findIndex(item => item == '追踪邮件'), 1)
                }
                if (this.form.emailSendTiming) {//存在 - 不为空
                    this.isTimeSend = true;
                    this.checkList.push('定时发送');
                }
                this.form.senderEmail = detail.userEmail;
                if (detail.boxId == 0) {//收件箱
                    this.form.senderNickName = this.userInfo.account;//获取用户名
                } else {
                    this.form.senderNickName = detail.senderNickName;
                }
                //收件箱
                let sendMan;
                if (detail.emailType == 1) {//收件箱
                    sendMan = detail.userEmail;
                } else {
                    sendMan = detail.senderEmail;
                }
                let params = {
                    senderEmail: sendMan,//发件人
                    addresseeEmail: detail.addresseeEmail ? detail.addresseeEmail.split(",") : [],//收件人
                    isCarbonCopy: this.form.emailCarbonCopy.length == 0 ? false : true,
                    emailCarbonCopy: detail.emailCarbonCopy ? detail.emailCarbonCopy.split(",") : [],//抄送
                    isSecretDelivery: (this.form.emailSecretDelivery.length == 0 || detail.boxId == 3) ? false : true,
                    emailSecretDelivery: (detail.emailSecretDelivery && (detail.boxId == 3 || detail.boxId == 2)) ? detail.emailSecretDelivery.split(",") : [],//密送
                    emailSubject: this.form.emailSubject,//主题
                    monocular: this.form.monocular == 1 ? true : false
                }
                //初始化顶部组件
                this.$refs.write.init(params)
                //初始化编辑器
                this.$refs.childEdit.getInit(this.form.emailContent);
                this.$refs.makeBtn.init({
                    emailHtmlpicList: this.form.emailHtmlpicList,
                    monocular: this.form.monocular == 1 ? true : false
                });
            },
            //取消按钮回调
            getCancel(params) {
                this.form = Object.assign({}, this.form, params);
                if (this.form.addresseeEmail.length != 0 && this.form.emailSubject != '' && (this.form.senderEmail != '') && !this.common.isExpired) {
                    this.$confirm(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">您正在编辑内容，是否保存至草稿箱？</p>\n' +
                        '      </div>', '保存邮件到草稿箱', {
                        dangerouslyUseHTMLString: true,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        confirmButtonText: '保 存',
                        cancelButtonText: '不保存',
                    }).then(() => {
                        this.sendEmail(this.form.sendType)
                        this.$router.push('/mail/index')
                    }).catch(() => {
                        this.$router.push('/mail/index')
                    })
                } else {
                    this.$router.push('/mail/index')
                }
            },
            insertEditor(val,type) {
                if(type==1){
                    this.form.emailContent += val;
                }else if(type==0){
                    this.form.emailContent = val + this.form.emailContent;
                }else if(type==2){
                    this.form.emailContent=val;
                }
                this.$refs.childEdit.getInit(this.form.emailContent);
                this.$refs.makeBtn.getContent(this.form.emailContent);
            },
            getInfoMake(params) {
                this.form = Object.assign({}, this.form, params)
            },
            getInfoWrite(params) { //顶部数据 - 点击发送按钮触发
                this.form = Object.assign({}, this.form, params);
                this.sendEmail(params.sendType)
            },
            getSendEmail(email) {
                this.form.senderEmail = email;
            },
            //预览
            review(params) {
                let info = Object.assign({}, this.form, params);
                let routeUrl = this.$router.resolve({
                    name: '/mail/write/Review',
                    query: {
                        info: JSON.stringify(info)
                    }
                });
                window.open(routeUrl.href, '_blank');
            },
            cancel() {
                this.$confirm('您正在写信，是否离开写信页面?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    this.$router.go(-1)
                }).catch(() => {
                    return;
                });
            },
            //提交审批
            toApproval(params) {
                this.form.emailReceipt = this.form.emaileDelivery = 0;
                this.checkList.map(item => {
                    if (item === '回执') {
                        this.form.emailReceipt = 1;
                    } else if (item === '紧急') {
                        this.form.emaileDelivery = 2;
                    } else if (item === '追踪邮件') {
                        this.form.emailTrack = 1;
                    }
                })
                this.form = Object.assign({}, this.form, params);
                if (this.getParams()) {
                    const target = JSON.parse(JSON.stringify(this.form));
                    this.$refs.dialogApproval.init(target);
                }
            },
            getParams() {
                if (this.form.senderEmail == '') {
                    this.$message({
                        duration: 1500,
                        message: '请选择发件人邮箱',
                        type: "success"
                    });
                    return false
                } else if (this.form.addresseeEmail.length === 0) {
                    this.$message({
                        duration: 1500,
                        message: '请输入收件人邮箱',
                        type: "success"
                    });
                    return false
                } else if (!this.form.emailSubject) {
                    this.$message({
                        duration: 1500,
                        message: '请输入主题',
                        type: "success"
                    });
                    return false
                } else if (!this.form.emailContent) {
                    this.$message({
                        duration: 1500,
                        message: '请输入邮件内容',
                        type: "success"
                    });
                    return false
                } else {
                    return true
                }
            },
            //发送邮件
            sendEmail(type) {
                if (this.form.senderEmail == '') {
                    this.$message({
                        duration: 1500,
                        message: '请选择发件人邮箱',
                        type: "success"
                    });
                    return;
                } else if (this.form.addresseeEmail.length === 0) {
                    this.$message({
                        duration: 1500,
                        message: '请输入收件人邮箱',
                        type: "success"
                    });
                    return;
                }
                if (type != 2) {
                    if (!this.form.emailSubject) {
                        this.$message({
                            duration: 1500,
                            message: '请输入主题',
                            type: "success"
                        });
                        return;
                    }
                }
                //判断群发单线个数  30
                let msg = '';
                if (this.form.emailSecretDelivery.length > 20) {
                    msg = '密送人最多不超过20个！'
                }
                if (this.form.emailCarbonCopy.length > 20) {
                    msg = '抄送人最多不超过20个！'
                }
                if (this.form.addresseeEmail.length > 30) {
                    msg = '收件人最多不超过30个！'
                }
                if (msg) {
                    this.$confirm(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;font-size: 14px;">' + msg + '</p></div>', '提示', {
                        dangerouslyUseHTMLString: true,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        confirmButtonText: '确 定',
                    }).then(() => {
                        return;
                    }).catch(() => {
                        return;
                    })
                }
                //处理参数
                this.form.emailTrack=this.form.emailReceipt = this.form.emaileDelivery = 0;
                let state = true;
                this.checkList.map(item => {
                    if (item === '回执') {
                        this.form.emailReceipt = 1;
                    } else if (item === '紧急') {
                        this.form.emaileDelivery = 2;
                    } else if (item === '追踪邮件') {
                        this.form.emailTrack = 1;
                    } else if (item === '定时发送') {
                        if (this.form.emailSendTiming == '') {
                            state = false;
                            this.$message({
                                duration: 1500,
                                message: '请选择定时发送时间',
                                type: "success"
                            });
                        }
                    }
                })
                if (!state) {
                    return;
                }

                this.form.emailContent = encodeURIComponent(this.form.emailContent);
                this.form.boxId = type ? type : '';
                this.toSend();
            },
            toSend() {
                if (this.content) {//编辑
                    this.form = Object.assign({}, this.form, {temailInfoId: JSON.parse(this.content).temailInfoId})
                }
                const boxID = this.form.boxId;
                const monocular = this.form.monocular;
                const emailSendTiming = this.form.emailSendTiming;
                this.isLoading = true;
                sendEmail(this.form).then(res => {
                    this.isLoading = false;
                    if (res.data.success) {
                        this.bus.$emit('refreshEmailNum')
                        if (boxID == 2) {//存草稿
                            this.$message({message: res.data.msg, type: 'success'});
                            this.reset()
                        } else {
                            this.isComplete = {
                                id: res.data.data,
                                oldID: this.id,
                                monocular: monocular,
                                emailSendTiming: emailSendTiming,
                                name: this.name,
                                title: this.form.emailSubject
                            };
                            let title = this.name == 'emailListCustomerTab' ? 'successCustomerInbox' : 'successInbox';
                            this.$refs[title].init(this.isComplete)
                        }
                    } else {
                        this.form.emailContent = decodeURIComponent(this.form.emailContent);
                    }
                }).catch(err => {
                    this.isLoading = false;
                    this.form.emailContent = decodeURIComponent(this.form.emailContent);//防止二次提交
                })
            },
            //重置数据
            reset() {
                //结束 - 关闭页面
                let list = [], arr = [], index, target = '';
                list = this.common[this.name].list;
                for (let i in list) {
                    const item = list[i];
                    if (item.id != JSON.parse(this.info).emailOriginalId) {
                        arr.push(item)
                    } else {
                        index = i;
                    }
                }
                if (this.name == 'emailListTab') {//收件箱
                    target = 'SET_EMAILLISTTAB'
                } else if (this.name == 'emailListUnreadTab') {//未读信箱
                    target = 'SET_EMAILLISTUNREADTAB'
                } else if (this.name == 'emailListOutTab') {//已发送箱
                    target = 'SET_EMAILLISTOUTTAB'
                } else if (this.name == 'emailListPendingTab') {//待处理
                    target = 'SET_EMAILLISTPENDINGTAB'
                } else if (this.name == 'emailListCustomerTab') {//待处理
                    target = 'SET_EMAILLISTCUSTOMERTAB'
                }
                this.$store.commit(target, {
                    type: 2, list: arr, index: index
                })
            },
            getRightTime(time) {//回调时间
                this.form.emailSendTiming = time;
                if (time == '') {
                    const index = this.checkList.indexOf("定时发送");
                    this.checkList.splice(index, 1);
                }
            },
            getArrDifference(arr1, arr2) {
                return arr1.concat(arr2).filter(function (v, i, arr) {
                    return arr.indexOf(v) === arr.lastIndexOf(v);
                });
            }
        }
    }
</script>

<style lang="scss">
  $bgActiveColor: #E9F3FD;
  $fontColor: #2A97F9;
  $lineColor: #F3F3F3;
  .write {
    margin: 10px 0;
    border-radius: 10px;
    background-color: #fff;
    height: auto;

    button.el-button.el-button--default {
      line-height: 30px;
      padding: 0 15px;

      i {
        margin-right: 5px;
      }
    }

    button.el-button.el-button--default.active {
      background-color: $bgActiveColor;
      color: $fontColor;
    }

    .info {
      margin-bottom: 10px;
      display: flex;
      align-items: center;

      h1 {
        font-size: 14px;
        color: #1B2242;
        margin-right: 30px;
      }
    }

    .make-btn {
      margin-bottom: 15px;
    }
  }

</style>


